package com.parleys.service;

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.parleys.exception.WebserviceNotAvailableException;
import com.parleys.service.intf.ParleysHTTPClient;
import com.parleys.service.intf.RestClient;

@Singleton
public class RestClientImpl implements RestClient {

	private static final String TAG = RestClientImpl.class.getName();

	private ParleysHTTPClient parleysHTTPClient;

	@Inject
	public RestClientImpl(final ParleysHTTPClient parleysHTTPClient) {
		this.parleysHTTPClient = parleysHTTPClient;
	}

	public List<JSONObject> get(final String url) throws WebserviceNotAvailableException {

		ArrayList<JSONObject> resultList = new ArrayList<JSONObject>();
		Reader reader = null;

		try {
			String result = parleysHTTPClient.getContentAsString(url);
			JSONArray jsonArray = new JSONArray(result);
			for (int i = 0; i < jsonArray.length(); i++) {
				resultList.add((JSONObject) jsonArray.get(i));
			}
		} catch (ClientProtocolException e) {
			Log.e(TAG, "Error while performing GET", e);
		} catch (IOException e) {
			Log.e(TAG, "Error while performing GET", e);
			throw new WebserviceNotAvailableException(e);
		} catch (JSONException e) {
			Log.e(TAG, "Error while performing GET", e);
		} finally {
			IOUtils.closeQuietly(reader);
		}

		return resultList;
	}

}
